<template>
  <div class="edit">
    <div>
      <h2>产品新增/编辑</h2>
      <p><span>产品名称:</span><input type="text" v-model="pro.pname" /></p>
      <p>
        <span>产品编号: </span
        ><input type="text" v-model="pro.id" :disabled="disabled" />
      </p>
      <p><span>成本价:</span><input type="text" v-model="pro.price" /></p>
      <p><span>库存数:</span><input type="text" v-model="pro.count" /></p>
      <p><span>登记人:</span><input type="text" v-model="pro.user" /></p>
      <p>
        <button @click="save">保存</button>
        <button>取消</button>
      </p>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      pro: {
        pname: "xxx",
        id: 0,
        uptDate: new Date(),
        price: 0,
        count: 0,
        user: "hjx",
        isShow: true,
      },
      disabled: true, 
    };
  },
  created() {
    this.disabled = Boolean(this.$route.query.id);
    if (this.disabled) {
      let idx = this.arr.findIndex((item) => item.id == this.$route.query.id);
      this.pro = { ...this.arr[idx] };
    }
  },
  computed: {
    ...mapState(["arr"]),
  },
  methods: {
    ...mapMutations(["addPro", "editPro"]),
    save() {
      if (this.disabled) {
        this.pro.uptDate = new Date();
        this.editPro(this.pro);
      } else {
        console.log("新增", this.pro);
        this.addPro(this.pro);
      }
      localStorage.setItem("arr", JSON.stringify(this.arr));
      this.$router.push("/home/products");
    },
  },
};
</script>

<style lang="less" scoped>
.edit {
  padding: 20px;
  h2 {
    text-align: center;
    line-height: 50px;
  }
  div {
    width: 350px;
    margin: 0 auto;
  }
  p {
    text-align: center;
    line-height: 35px;
    span {
      display: inline-block;
      width: 100px;
    }
    input {
      width: 200px;
    }
    button {
      width: 100px;
      margin-right: 10px;
      line-height: 30px;
    }
  }
}
</style>